<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4">
        <div v-if="deptOptions.length">
          <el-input v-model="deptName" placeholder="请输入文件名称" clearable size="small"
            prefix-icon="Search" style="margin-bottom: 20px;height: 40px;" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="true"
            :filter-node-method="filterNode" ref="tree" node-key="id" highlight-current
            @node-click="handleNodeClick" :current-node-key='defaultkey' class="custom-treeF"
            @node-contextmenu='contextmenu' :default-expanded-keys='defaultkeyarr'
            @node-expand='unfold' @node-collapse='closeTree' :auto-expand-parent='false'>
            <template #empty>
              <div v-if="!deptOptions.length" class="custom-empty-text">
                <p>{{emptyText}}</p>
                <el-button icon="Plus" size="large" @click="addFolder" />
              </div>
            </template>
            <template #default="{ node, data }">
              <el-popover placement="top" :visible='data.id === rightClickNodeId'>
                <div><el-button text type='danger' @click="handleDelete(node, data)">删除</el-button>
                </div>
                <el-button text type='primary' @click="handleEidt(node, data)">修改</el-button>
                <template #reference>
                  <span class="custom-tree-node">
                    <span>{{ node.label }}
                      &nbsp;
                      {{data.picNum <=0?'':(data.picNum)}}
                    </span>
                    <span v-if="defaultkey==data.id && indexLeave <3">
                      <el-button icon="Plus" size="small" @click.stop="addFolder" />
                    </span>
                  </span>
                </template>
              </el-popover>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :xs="24" :sm="20" :md="20" :lg="20" :xl="20" class="colParentLevel">
        <el-empty :description="emptyText" v-if="!deptOptions[0].children.length" class="emptyNumm">
          <el-button type="primary" icon="Plus" plain @click="addFolder2"></el-button>
        </el-empty>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <div class="fontBottom" v-if="  indexLeave>=3">
              <div class="compile">
                <!-- <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
              @change="handleCheckAllChange" v-show="checSta">暂时 -->
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange" v-if="deptOptions5.length !=0">
                  全选
                </el-checkbox>

                <el-button type="danger" plain v-show="checkedCities.length !=0" @click="delImage"
                  class="deleteButn">删除</el-button>
                <!-- <el-button type="danger" text circle v-show="checSta" @click="delImage">删除</el-button> -->
                <!-- <el-button text type='primary' v-show="checSta" @click="accomplish">
              完成
            </el-button> -->
                <!-- <el-button type="primary" icon="Edit" circle v-show="!checSta" @click="EditSta" /> -->
                <el-button type="success" plain @click="dragHaul">上传图片</el-button>
              </div>
              <!-- <el-upload ref="uploadRef" class="upload-demo" action="" :auto-upload="false"
            :on-change="(file) => {successUpload(file)}" :show-file-list='false'
            accept='.jpg, .png, .jpeg'>
            <template #trigger>
              <el-button type="primary" icon="Plus" plain>上传图片</el-button>
            </template>
          </el-upload> -->
            </div>

          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-row :gutter="20" :style="tableHeight" class="el-rowHight">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(item,index) in deptOptions3"
                :key="index" class="floCol" v-show="deptOptions5.length==0"
                @click="handleNodeClick(item)">
                <el-card body-class='el-cardFol'>
                  <el-badge
                    :value="item.picNum==null||item.picNum==0 ||item.picNum==undefined ?'':item.picNum"
                    class="item">
                    <el-icon>
                      <FolderOpened />
                    </el-icon>
                  </el-badge>
                  <template #footer>
                    {{item.label}}
                  </template>
                </el-card>
              </el-col>
              <el-col :span="4" v-for="(item,index) in deptOptions5" :key="index" class="floCol"
                v-show="deptOptions5.length !=0" :xs="24" :sm="12" :md="8" :lg="6" :xl="4">

                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange"
                  v-if="item.label ==undefined">
                  <el-card body-class='el-cardFol'>
                    <!-- <template #header v-if="checSta"> -->
                    <el-checkbox :value="item.id" class="headCheckbox">
                    </el-checkbox>
                    <!-- </template> -->
                    <el-image style="width: 100%; height:74px"
                      :src="'https://jzh-newhxd.oss-cn-qingdao.aliyuncs.com/'+item.picUrl"
                      :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                      :preview-src-list="['https://jzh-newhxd.oss-cn-qingdao.aliyuncs.com/'+item.picUrl]"
                      :initial-index="0" fit="contain" hide-on-click-modal />
                    <template #footer>
                      {{item.picName}}
                    </template>
                  </el-card>
                </el-checkbox-group>
                <el-card body-class='el-cardFol' v-else @click="handleNodeClick(item)">
                  <el-badge
                    :value="item.picNum==null||item.picNum==0 ||item.picNum==undefined ?'':item.picNum"
                    class="item">
                    <el-icon>
                      <FolderOpened />
                    </el-icon>
                  </el-badge>
                  <template #footer>
                    {{item.label}}
                  </template>
                </el-card>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <div v-if="deptOptions[0].children.length !=0">
          <el-empty
            :description="indexLeave==0?emptyText:indexLeave==1?emptyText0:indexLeave==2?emptyText3:emptyText2"
            v-if="fileSATS||fileSATInsex" class="emptyNumm">
            <!-- <el-upload ref="uploadRef" class="upload-demo" action="" :auto-upload="false"
              :on-change="(file) => {successUpload(file)}" :show-file-list='false'
              accept='.jpg, .png, .jpeg' v-if="fileSATInsex ||indexLeave==3">
              <template #trigger>
                <el-button type="primary" icon="Plus" plain>{{indexLeave==2?'图片':"图片"}}</el-button>
              </template>
            </el-upload> -->
            <!-- <el-button type="success" plain @click="dragHaul"
              v-if="fileSATInsex ||indexLeave==3">{{indexLeave==2?'图片':"图片"}}</el-button> -->
            <el-button type="primary" icon="Plus" plain @click="addFolder2"
              v-if="fileSATS ||indexLeave==2">{{indexLeave==2?'文件夹':"文件夹"}}</el-button>
          </el-empty>
        </div>

      </el-col>
    </el-row>
    <el-dialog v-model="dialogFormVisible" title="添加文件夹" width="30%" :close-on-click-modal='false'>
      <el-form :model="form" label-width="auto" ref="ruleFormRef" :rules="rules">
        <el-form-item label="归属文件夹" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="deptOptions2"
            :props="{ value: 'id', label: 'label', children: 'children', disabled:'disabled' }"
            value-key="id" placeholder="请选择归属文件夹" check-strictly filterable default-expand-all />
        </el-form-item>
        <el-form-item label="文件夹名称" prop='folderName'>
          <el-input v-model.trim="form.folderName" autocomplete="off" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelFolder">取消</el-button>
          <el-button type="primary" @click="confirmFolder">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="visibleUnpImag" :show-close="false">
      <template #header="{  titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">拖拽上传</h4>
          <el-button type="danger" @click="close" icon="Close" />
        </div>
      </template>
      <el-upload class="upload-demo upload-demo2" drag action="" multiple :auto-upload="false"
        v-model:file-list="fileList" list-type="picture">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽图片或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png/jpeg
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer" v-if="fileList.length !=0">
          <el-button @click="cancelDrag">取消</el-button>
          <el-button type="primary" @click="submitDrag" :loading="loading">
            {{loading==true?'...提交中':'确定'}}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="visibleEiet" :show-close="false" width="500" :close-on-click-modal='false'>
      <template #header="{  titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">修改文件名称</h4>
          <el-button type="danger" @click="closeWJJ" icon="Close" />
        </div>
      </template>
      <el-form :model="formEidt" ref="ruleFormRefEidt" :rules="rulesEidt">
        <el-form-item label="文件名称" prop="folderNameEidt">
          <el-input v-model="formEidt.folderNameEidt" autocomplete="off" placeholder="请输入文件名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeWJJ">取消</el-button>
          <el-button type="primary" @click="confirmEidt">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name='ImageAdmin'>
import { ElMessage, ElMessageBox } from "element-plus";
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  toRaw,
  nextTick,
  watch,
} from "vue";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
import {
  creationFolder,
  FolderList,
  deleteFolder,
  uploadImage,
  fileImageList,
  deletedircPiD,
} from "@/api/commodityMgt/imageAdmin/imageAdmin";
const visibleUnpImag = ref(false);
const fileList = ref([]); //拖拽上传列表
const checSta = ref(false);
const loading = ref(false);
const checkAll = ref(false); //全选
const isIndeterminate = ref(false);
const checkedCities = ref([]);
const defaultkeyarr = ref([-1]); //默认展开的 节点
const visibleEiet = ref(false);
// 动态计算表格高度
const tableHeight = ref({
  "max-height": "calc(100vh - 140px)",
}); // 假设顶部保留200px
function handleResize(sta) {
  let hight = 200 + "px";
  let hight2 = "";
  if (sta == 2) {
    hight2 = 184 + "px";
  } else {
    hight2 = 140 + "px";
  }
  tableHeight.value = {
    "max-height": `calc(100vh - ` + hight2 + `)`,
  };
  let elTreeNodeChildren =
    document.querySelector(".custom-treeF").children[0].children;
  for (var i = 0; i < elTreeNodeChildren.length; i++) {
    if (i == 1) {
      elTreeNodeChildren[i].className += " classnameTree";
      elTreeNodeChildren[i].style.maxHeight = `calc(100vh - ` + hight + `)`;
    }
  }
}

onMounted(async () => {
  await nextTick();
  handleResize();
  window.addEventListener("resize", handleResize);
});
// 移除事件监听器以防止内存泄漏
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
// 树形结构展开
const unfold = (node) => {
  if (!defaultkeyarr.value.includes(node.id)) {
    defaultkeyarr.value.push(node.id);
  }
  handleResize();
};
const arrrID = ref([]);
// 树形结构关闭
const closeTree = (node) => {
  if (node.id == -1) {
    defaultkeyarr.value = [];
  } else {
    arrrID.value = [];
    addLevelToTree3([node]);
    for (let i = arrrID.value.length - 1; i >= 0; i--) {
      const index = defaultkeyarr.value.indexOf(arrrID.value[i]);
      if (index > -1) {
        defaultkeyarr.value.splice(index, 1);
      }
    }
  }
};

function addLevelToTree3(treeData) {
  // 遍历树形数据
  treeData.forEach((item) => {
    // 给当前项添加level属性
    arrrID.value.push(item.id);
    // 如果有子项，则递归处理子项，同时level值增加1
    if (item.children && item.children.length > 0) {
      addLevelToTree3(item.children);
    }
  });
  return arrrID;
}
// 关闭文件夹
const closeWJJ = () => {
  visibleEiet.value = false;
};
// 拖拽上传
const dragHaul = () => {
  visibleUnpImag.value = true;
};
// 提交拖拽上传
async function submitDrag() {
  loading.value = true;
  for (let i = fileList.value.length - 1; i >= 0; i--) {
    let formData = new FormData();
    formData.append("file", fileList.value[i].raw);
    formData.append("picId", defaultkey.value);
    await uploadImage(formData);
    proxy.$modal.msgSuccess(fileList.value[i].name + "添加成功");
    fileList.value.splice(i, 1);
  }
  loading.value = false;
  FolderListPost(2);
  fileImageListPost({
    dicId: defaultkey.value,
  });
}
const close = () => {
  loading.value = false;
  fileList.value = [];
  visibleUnpImag.value = false;
};
// 取消拖拽上传
const cancelDrag = () => {
  loading.value = false;
  fileList.value = [];
  visibleUnpImag.value = false;
};
// 全选
const handleCheckAllChange = (val) => {
  let IDlist = [];
  for (let i = 0; i < deptOptions5.value.length; i++) {
    IDlist.push(deptOptions5.value[i].id);
  }
  checkedCities.value = val ? IDlist : [];
  isIndeterminate.value = false;
};
// 是否选着
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === deptOptions5.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < deptOptions5.value.length;
};
// 完成
const accomplish = () => {
  checkedCities.value = [];
  checkAll.value = false;
  checSta.value = false;
};
// 编辑
const EditSta = () => {
  checSta.value = true;
};
// 删除
const delImage = () => {
  if (checkedCities.value.length == 0) {
    proxy.$modal.msgWarning("请选择要删除的图片");
  } else {
    ElMessageBox.confirm("是否要删除所选中的图片", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deletedircPiD(checkedCities.value)
          .then((res) => {
            proxy.$modal.msgSuccess("删除成功");
            checkedCities.value = [];
            checkAll.value = false;
            isIndeterminate.value = false;
            FolderListPost(2);
            fileImageListPost({
              dicId: defaultkey.value,
            });
          })
          .catch((err) => {});
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消",
        });
      });
  }
};

const deptName = ref("");
const deptOptions = ref([
  {
    id: -1,
    label: "图片列表",
    children: [],
  },
]); // 文件夹树选项
const deptOptions2 = ref([
  {
    id: -1,
    label: "图片列表",
    children: [],
  },
]); // 文件夹树选项
const deptOptions3 = ref([]); // 文件夹树选项
const deptOptions4 = ref([]); // 文件夹树选项
const deptOptions5 = ref([]); // 文件夹树选项
const dialogFormVisible = ref(false);
const defaultkey = ref(-1);
const rightClickNodeId = ref(null);
const emptyText0 = ref("你还未创建商品分类文件夹，请先创建一个吧");
const emptyText = ref("你还未创建品牌分类文件夹，请先创建一个吧");
const emptyText2 = ref("还没有任何图片 请先添加一张吧");
// const emptyText3 = ref("请先创建一个图片归类文件夹 或者上传一张图片吧");
const emptyText3 = ref("请先创建一个图片归类文件夹");

const timeOut = ref("");
const indexLeave = ref(0);
const fileSATS = ref(false);
const clickSta = ref(false);
const fileSATInsex = ref(false);
const defaultProps = ref({
  children: "children",
  label: "label",
});
// 筛选节点
// const filterNode = (value, data, node) => {
//   if (!value) return true;
//   let parentNode = node.parent;
//   let labels = [node.label];
//   let level = 1;
//   while (level < node.level) {
//     labels = [...labels, parentNode.label];
//     parentNode = parentNode.parent;
//     level++;
//   }
//   return labels.some((label) => label.indexOf(value) !== -1);
// };

// 展开所有父级
const openSuperior = (node) => {
  if (node.parent) {
    node.parent.expanded = true;
    openSuperior(node.parent);
  }
};
const nodesParentId = ref([]);

const findTreeIdObjFn = (data, key, value) => {
  let temp = null;
  (function fn(data, value) {
    data.forEach((item) => {
      if (item[key] === value) {
        temp = item;
      }
      if (item.children && item.children.length > 0) {
        fn(item.children, value);
      }
    });
  })(data, value);
  return temp;
};
const findCurNodeDescendantsFn = (data, key, value) => {
  const obj = findTreeIdObjFn(data, key, value);
  const ids = [];
  (function selfRunFn(obj) {
    ids.push(obj[key]);
    if (obj.children && obj.children.length > 0) {
      obj.children.forEach((x) => {
        selfRunFn(x);
      });
    }
  })(obj);
  return ids;
};

const filterNode = (value, data, node) => {
  if (value == "") {
    return true;
  }
  // 校验没有数据情况
  if (!value) {
    nodesParentId.value = [];
    nextTick(() => {
      node.expanded = false;
    });
    return true;
  }

  // 控制展开和收起
  nextTick(() => {
    node.expanded = false;
  });
  // 当前名字是否包含在上级父亲里
  if (data.label.indexOf(value) !== -1) {
    nextTick(() => {
      openSuperior(node);
      // 如果是第一级，直接打开当前级
      if (!data.parentId) {
        node.expanded = false;
      }
    });
  }

  // 隐藏所有支线节点下面的所有子节点
  // 思路：
  // （当前是支线节点，兄弟有匹配到的情况）并且 （支线节点所有下级都匹配不到）的情况
  //  隐藏支线节点，包括所有下级的子节点才行，光隐藏支线节点没有用
  if (node.level > 1) {
    // 把我和兄弟name整合到数组中
    const info = findTreeIdObjFn(deptOptions.value, "id", data.id).children.map(
      (d) => d.label
    );
    //  判断兄弟有没有
    if (info.some((d) => d.indexOf(value) !== -1)) {
      // 兄弟能匹配到，自己没有匹配到
      if (data.label.indexOf(value) === -1) {
        // 下级的 name 集合
        const names = findCurNodeDescendantsFn(
          deptOptions.value,
          "id",
          data.id
        ).map((d) => findTreeIdObjFn(deptOptions.value, "id", d).label);
        // 判断都没匹配到的情况
        if (!names.some((d) => d.indexOf(value) !== -1)) {
          // 把我和我下级所有id push到变量中，将当前支线节点隐藏
          nodesParentId.value.push(
            ...findCurNodeDescendantsFn(deptOptions.value, "id", data.id)
          );
          return false;
        }
      }
    }
  }
  // 当前节点在支线节点名单中，则隐藏当前节点
  if (nodesParentId.value.indexOf(data.id) !== -1) {
    return false;
  }

  // 子级可被筛选到
  let parentNode = node.parent; // 父级node
  let labels = [node.label]; // 当前node的名字
  let level = 1; // 层级
  while (level < node.level) {
    labels = [...labels, parentNode.label]; // 当前node名字，父级node的名字
    parentNode = parentNode.parent;
    level++;
  }
  return labels.some((d) => d.indexOf(value) !== -1);
  // 总结：之前没解决的是因为 只隐藏支线父节点是隐藏不掉的，隐藏父节点包括下面的所有子节点才能隐藏
};

// 监听输入框
watch(deptName, (val) => {
  proxy.$refs.tree.filter(val);
});

// ------------------------------------------------------------------------------------------------
// 监听输入框
watch(defaultkey, (val) => {
  upflod();
});

watch(deptOptions5, (val) => {
  if (val.length == 0) {
    checSta.value = false;
  }
});
watch(clickSta, (val) => {
  fileSATInsex.value = false;
  switch (indexLeave.value) {
    case 0:
      fileSATS.value = false;
      break;
    case 1:
      if (deptOptions3.value.length == 0) {
        fileSATS.value = true;
      } else {
        fileSATS.value = false;
      }
      break;
    case 2:
      if (deptOptions3.value.length == 0 && deptOptions5.value.length == 0) {
        fileSATS.value = true;
      } else {
        fileSATS.value = false;
      }
      break;
    case 3:
      fileSATS.value = false;
      if (deptOptions5.value.length == 0) {
        fileSATInsex.value = true;
      }
      break;

    default:
      break;
  }
});
watch(indexLeave, (val) => {
  if (val == 3) {
    handleResize(2);
  }
});
// 节点单击事件
const handleNodeClick = (data, node, self) => {
  if (defaultkey.value == data.id) {
    return false;
  }
  indexLeave.value = data.level;
  if (data.id == -1 || data.level <= 1) {
    deptOptions5.value = [];
    if (defaultkeyarr.value.includes(data.id) == false) {
      defaultkeyarr.value.push(data.id);
    }
    const node = proxy.$refs.tree.store.nodesMap[data.id];
    if (node) {
      proxy.$refs.tree.store.nodesMap[data.id].expanded = true;
    }
  } else {
    fileImageListPost({
      dicId: data.id,
    });
  }
  defaultkey.value = data.id;
};
// 图片列表
const fileImageListPost = (data) => {
  fileImageList(data)
    .then((res) => {
      fileSATInsex.value = false;
      if (res.data.length == 0 && deptOptions3.value.length == 0) {
        if (indexLeave.value == 3) {
          fileSATS.value = false;
          fileSATInsex.value = true;
        } else {
          fileSATS.value = true;
        }
      } else {
        fileSATS.value = false;
      }
      deptOptions5.value = res.data;
      deptOptions5.value = deptOptions3.value.concat(deptOptions5.value);
    })
    .catch((err) => {});
};

const validateNoSpace = (rule, value, callback) => {
  if (value == "") {
    callback(new Error("文件夹名称不能为空"));
  } else if (value.trim() === "") {
    callback(new Error("输入不能全是空格"));
  } else {
    callback();
  }
};
const data = reactive({
  form: {
    folderName: "",
    deptId: "",
  },
  queryParams: {
    shopId: userStore.userDta.shopId,
    page: 1,
    limit: 1000,
  },
  rules: {
    folderName: [
      { required: true, validator: validateNoSpace, trigger: "blur" },
    ],
    deptId: [
      {
        required: true,
        message: "请选择归属文件夹",
        trigger: "change",
      },
    ],
  },
  formEidt: {
    folderNameEidt: "",
    folderId: "",
  },
  rulesEidt: {
    folderNameEidt: [
      { required: true, validator: validateNoSpace, trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules, formEidt, rulesEidt } = toRefs(data);
// 文件夹列表
const FolderListPost = (sta) => {
  FolderList({
    shopId: queryParams.value.shopId,
  }).then((res) => {
    let folderList = JSON.stringify(res.data);
    deptOptions2.value[0].children = JSON.parse(folderList);
    deptOptions2.value = addLevelToTree(deptOptions2.value, 1);
    deptOptions3.value = res.data;
    deptOptions4.value = res.data;
    deptOptions.value[0].children = res.data;
    deptOptions.value = addLevelToTree(deptOptions.value, 2);
    if (sta == 2) {
      upflod();
    }
  });
};
function addLevelToTree(treeData, sta, level = 0) {
  // 遍历树形数据
  treeData.forEach((item) => {
    // 给当前项添加level属性
    item.level = level;
    if (item.level == 2 && sta == 1) {
      // item.disabled = true;
      delete item.children;
    }
    // 如果有子项，则递归处理子项，同时level值增加1
    if (item.children && item.children.length > 0) {
      addLevelToTree(item.children, sta, level + 1);
    }
  });
  return treeData;
}
const arrTree = ref([]);
function addLevelToTree2(treeData, id) {
  // 遍历树形数据
  treeData.forEach((item) => {
    // 给当前项添加level属性
    if (item.id == id) {
      arrTree.value = toRaw(item.children);
      return;
    }
    // 如果有子项，则递归处理子项，同时level值增加1
    if (item.children && item.children.length > 0) {
      addLevelToTree2(item.children, id);
    }
  });
  return arrTree;
}
const upflod = () => {
  if (defaultkey.value == -1) {
    deptOptions3.value = deptOptions4.value;
  } else {
    deptOptions3.value = toRaw(
      addLevelToTree2(deptOptions4.value, defaultkey.value).value
    );
  }
  fileImageListPost({
    dicId: defaultkey.value,
  });
  nextTick(() => {
    clickSta.value = !clickSta.value;
    proxy.$refs.tree.setCurrentKey(defaultkey.value);
  });
};
// 文件上传
const successUpload = (file) => {
  let formData = new FormData();
  formData.append("file", file.raw);
  formData.append("picId", defaultkey.value);
  uploadImage(formData)
    .then((res) => {
      proxy.$modal.msgSuccess("添加成功");
      FolderListPost(2);
      fileImageListPost({
        dicId: defaultkey.value,
      });
    })
    .catch((err) => {});
};

// 新增文件夹
const addFolder = () => {
  reset();
  if (indexLeave.value == 3) {
    return false;
    form.value.deptId = -1;
  } else {
    form.value.deptId = defaultkey.value;
  }
  dialogFormVisible.value = true;
};
const addFolder2 = () => {
  proxy.resetForm("ruleFormRef");
  form.value.deptId = defaultkey.value;
  dialogFormVisible.value = true;
};
// 取消
const cancelFolder = () => {
  reset();
  dialogFormVisible.value = false;
};
// 确定
const confirmFolder = () => {
  proxy.$refs.ruleFormRef.validate((valid, fields) => {
    if (valid) {
      creationFolder({
        label: form.value.folderName, //文件夹 名称
        shopId: queryParams.value.shopId, //店铺ID
        parentId: form.value.deptId == -1 ? 0 : form.value.deptId, //文件夹结构ID
      }).then((res) => {
        defaultkeyarr.value.push(form.value.deptId);
        const node = proxy.$refs.tree.store.nodesMap[form.value.deptId];
        if (node) {
          proxy.$refs.tree.store.nodesMap[form.value.deptId].expanded = true;
        }
        dialogFormVisible.value = false;
        proxy.$modal.msgSuccess("创建成功");
        FolderListPost(2);
        handleResize();
      });
    }
  });
};
// 修改文件夹
const handleEidt = (node, data) => {
  visibleEiet.value = true;
  formEidt.value = {
    folderNameEidt: data.label,
    folderId: data.id,
  };
  if (timeOut.value) {
    clearTimeout(timeOut.value);
  }
  rightClickNodeId.value = "";
};
const confirmEidt = () => {
  proxy.$refs.ruleFormRefEidt.validate((valid, fields) => {
    if (valid) {
      creationFolder({
        label: formEidt.value.folderNameEidt, //文件夹 名称
        shopId: queryParams.value.shopId, //店铺ID
        // parentId: form.value.deptId == -1 ? 0 : form.value.deptId, //文件夹结构ID
        id: formEidt.value.folderId,
      }).then((res) => {
        defaultkeyarr.value.push(form.value.deptId);
        const node = proxy.$refs.tree.store.nodesMap[form.value.deptId];
        if (node) {
          proxy.$refs.tree.store.nodesMap[form.value.deptId].expanded = true;
        }
        dialogFormVisible.value = false;
        visibleEiet.value = false;
        proxy.$modal.msgSuccess("修改成功");
        FolderListPost(2);
        handleResize();
      });
    }
  });
};

// 删除文件夹
const handleDelete = (node, data) => {
  rightClickNodeId.value = "";
  clearTimeout(timeOut.value);
  let text = "是否要删除 " + data.label + " 文件夹";
  ElMessageBox.confirm(text, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteFolder({
        dicId: data.id,
      }).then((res) => {
        deptOptions3.value = [];
        deptOptions5.value = [];
        indexLeave.value = 0;
        defaultkey.value = -1;
        if (defaultkey.value == data.id) {
          FolderListPost();
        } else {
          FolderListPost(2);
        }
        proxy.$modal.msgSuccess("删除成功");
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
// 文件夹 右键
const contextmenu = (event, data, node, json) => {
  if (data.id == -1) {
    return false;
  } else {
    if (timeOut.value) {
      clearTimeout(timeOut.value);
    }
    rightClickNodeId.value = data.id;
    timeOut.value = setTimeout(() => {
      rightClickNodeId.value = "";
    }, 3000);
  }
};

/** 重置操作表单 */
function reset() {
  form.value = {
    folderName: "",
    deptId: "",
  };
  proxy.resetForm("ruleFormRef");
}

FolderListPost();
</script>

<style  scoped lang="scss">
.head-container {
  :deep(.classnameTree) {
    overflow-y: auto;
  }
  :deep(.classnameTree::-webkit-scrollbar) {
    width: 5px;
  }
  :deep(.classnameTree::-webkit-scrollbar-thumb) {
    background: rgb(214, 213, 213);
    border-radius: 10px;
  }
}
.colParentLevel {
  .fontBottom {
    height: 44px;
    .compile {
      min-width: 300px;
      display: flex;
      align-items: center;
      .deleteButn {
        margin-left: 20px;
      }
    }
  }
  .el-rowHight {
    overflow-y: auto;
  }

  .el-rowHight::-webkit-scrollbar {
    width: 5px;
  }
  .el-rowHight::-webkit-scrollbar-thumb {
    background: rgb(214, 213, 213);
    border-radius: 10px;
  }
}
:deep(.emptyNumm) {
  margin: 10% auto;
}
.custom-empty {
  text-align: center;
  padding: 20px;
  color: #909399;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.floCol {
  margin-bottom: 20px;
  cursor: pointer;
}
/* 高亮颜色 */
:deep(
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
  ) {
  background-color: rgb(9 99 241 / 88%);
  color: #ffffff;
  opacity: 0.75;
  border-radius: 15px;
}
:deep(.el-cardFol) {
  display: flex;
  justify-content: center;
  font-size: 50px;
  color: #7e7cff;
  position: relative;
  .headCheckbox {
    position: absolute;
    top: -1px;
    left: -1px;
    height: auto;
    .el-checkbox__inner {
      width: 20px;
      height: 20px;
    }
    .el-checkbox__inner:after {
      height: 11px;
      left: 7px;
    }
  }
}
:deep(.el-card__footer) {
  text-align: center;
  background: #f8f8f9;
  font-weight: 400;
  font-size: 14px;
  color: #333333;
  display: -webkit-box; /* 使用Webkit的盒子模型 */
  word-break: break-all;
  line-break: anywhere;
  -webkit-line-clamp: 2; /* 限制最多显示2行 */
  -webkit-box-orient: vertical; /* 设置盒子内容的排列方向为垂直 */
  overflow: hidden; /* 隐藏超出容器的内容 */
  text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
  max-height: 70px;
  line-height: 20px;
}
.my-header {
  h4 {
    margin: 0;
  }
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
.upload-demo2 {
  :deep(.el-upload-list) {
    max-height: calc(100vh - 500px);
    overflow-y: auto;
  }
  :deep(.el-upload-list::-webkit-scrollbar) {
    width: 5px;
  }
  :deep(.el-upload-list::-webkit-scrollbar-thumb) {
    background: rgb(214, 213, 213);
    border-radius: 10px;
  }
}
</style>